package com.example.administrator.shzs.fragment.shopdetails;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.utils.GoodsAnimUtil;
import com.example.administrator.shzs.utils.StartLogInUtils;
import com.example.administrator.shzs.utils.ToastUtils;
import com.example.administrator.shzs.adapter.GoodsCarAdapter;
import com.example.administrator.shzs.adapter.ShopContentAdapter;
import com.example.administrator.shzs.adapter.ShopSortAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.db.GoodsBean;
import com.example.administrator.shzs.db.GoodsDataBaseInterface;
import com.example.administrator.shzs.db.OperateGoodsDataBase;
import com.example.administrator.shzs.entity.ShopSortData;
import com.example.administrator.shzs.entity.SortContentData;
import com.example.administrator.shzs.ui.OrderActivity;
import com.example.administrator.shzs.ui.ShopActivity;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;


/**
 * 点菜页面
 */
public class DishesFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {


    /**
     * 商品分类
     */
    private List<ShopSortData.ShopDatalistBean> mSorts;

    /**
     * 分类内容
     */
    private List<SortContentData.FoodlistBean> mContents;

    /**
     * 分类内容   加载更多
     */
    private List<SortContentData.FoodlistBean> mMoreContents;

    private int page = 1;

    private List<SortContentData.FoodlistBean.StylelistBean> stylelistBeen;


    //分类适配器
    private ShopSortAdapter mShopSortAdapter;

    //分类内容填充适配器
    private ShopContentAdapter mShopContentAdapter;

    /**
     * 用户userId
     */
    private String userId;

    /**
     * 商家ID
     */
    private String shopId;

    /**
     * 商家店名
     */
    private String shopName;

    /**
     * 商家图片
     */
    private String shopImage;


    /**
     * 类别ID
     */
    private String sortId;


    private ShopSortData.ShopDatalistBean sortData;


    /**
     * 分类ListView
     */
    private ListView lvSort;

    /**
     * 分类填充的内容
     */
    private XRecyclerView lvContent;

    private Button mListSubmit;

    private TextView mListAllPrice;//商品结算时总价
    private TextView mListAllNum;//商品总数量

    /**
     * 数据操作接口
     */
    GoodsDataBaseInterface mGoodsDataBaseInterface = null;

    /**
     * 购物车布局
     */
    private RelativeLayout mCarLay;
    private Button btnGouWuche;//购物车小人
    private List<GoodsBean> goodsBeens;//购物车实体类
    private GoodsCarAdapter carAdapter;
    private LinearLayout llGoodsCar;//购物车弹窗布局
    private TextView tvClearGoodsCar;//清空购物车
    private RecyclerView lvGoodsCar;//弹窗购物车列表
    private LinearLayout llGoodsCarBack;//弹窗过购物车半透明部分

    //没有数据时显示的控件
    private TextView tvNotGoods;
    private String sendfree;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_dishes, null);

        View contentItem = View.inflate(getActivity(), R.layout.shop_content_item, null);

        //初始化数据库类
        mGoodsDataBaseInterface = OperateGoodsDataBase.getInstance();

        //初始化
        setViews(view, contentItem);


        //获取数据
        setData();

        //获取购物车数据
        getGoodsCarData();

        //监听
        setListeners();
        return view;
    }

    /**
     * 监听器
     */
    private void setListeners() {

        lvSort.setOnItemClickListener(this);//左边分类列表
        btnGouWuche.setOnClickListener(this);//购物车小人
        tvClearGoodsCar.setOnClickListener(this);//清空购物车
        llGoodsCarBack.setOnClickListener(this);//点击隐藏购物车
        mListSubmit.setOnClickListener(this);
    }

    /**
     * 分类列表
     */
    private void setSortAdapter() {

        mShopSortAdapter = new ShopSortAdapter(getActivity(), mSorts);
        lvSort.setAdapter(mShopSortAdapter);

        //默认加载第一项数据
        sortId = mSorts.get(0).getSortID();
        Log.e("Life", "商品分类sortId------------" + sortId);
        getContentDataFromServer(shopId, sortId, 1);
    }


    /**
     * 内容填充适配器  item点击事件
     */
    private void setSortContentAdapter() {

        mShopContentAdapter = new ShopContentAdapter(getActivity(), mContents, shopId);
        lvContent.setAdapter(mShopContentAdapter);

        //item点击事件----购物车
        mShopContentAdapter.setOnItemClickListener(new ShopContentAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(ShopContentAdapter.MyViewHolder holder) {//整个Item的监听
            }

            @Override
            public void onAddClick(ShopContentAdapter.MyViewHolder holder) {/**加号按钮监听**/


                //商品数量
                String numText = holder.tvNumber.getText().toString().trim();
                //价钱
                stylelistBeen = mContents.get(holder.getPosition() - 1).getStylelist();
                String price = stylelistBeen.get(0).getPrice() + "";
                //商品Id
                int goodsid = Integer.parseInt(mContents.get(holder.getPosition() - 1).getFoodID());
                //商品名
                String goodsName = mContents.get(holder.getPosition() - 1).getName();

                /** 点击加号更新数据*/
                if (numText.isEmpty() || numText.equals("0")) {//还没有商品
                    holder.ivJian.setVisibility(View.VISIBLE);
                    holder.tvNumber.setVisibility(View.VISIBLE);

                    //单个商品购物数量
                    int numner = mGoodsDataBaseInterface.saveGoodsNumber(getActivity(), Integer.parseInt(shopId), goodsid, goodsName, "1", price, userId);
                    holder.tvNumber.setText("" + numner);

                } else {//已有商品在原有基础上+1

                    //单个商品购物数量
                    int number = mGoodsDataBaseInterface.saveGoodsNumber(getActivity(), Integer.parseInt(shopId), goodsid, goodsName, String.valueOf(Integer.parseInt(numText) + 1), price, userId);
                    holder.tvNumber.setText("" + number);

                }

                /** 执行动画 */
                GoodsAnimUtil.setAnim(getActivity(), holder.ivAdd, mCarLay);

                /** 结束动画后   并统计购物总数和购物总价 */
                GoodsAnimUtil.setOnEndAnimListener(new OnEndAnim());

            }

            @Override
            public void onJianClick(ShopContentAdapter.MyViewHolder holder) {/**减号按钮监听**/
                //数量
                String numText = holder.tvNumber.getText().toString().trim();
                //价钱
                stylelistBeen = mContents.get(holder.getPosition() - 1).getStylelist();
                String price = stylelistBeen.get(0).getPrice() + "";
                //商品Id
                int goodsid = Integer.parseInt(mContents.get(holder.getPosition() - 1).getFoodID());
                //商品名
                String goodsName = mContents.get(holder.getPosition() - 1).getName();

                String number = "" + mGoodsDataBaseInterface.saveGoodsNumber(getActivity(), Integer.parseInt(shopId), goodsid, goodsName, String.valueOf(Integer.parseInt(numText) - 1), price, userId);
                holder.tvNumber.setText(number);

                /** 减完之后  数据为0 */
                numText = holder.tvNumber.getText().toString().trim();
                if (numText.equals("0")) {
                    holder.tvNumber.setVisibility(View.GONE);
                    holder.ivJian.setVisibility(View.GONE);

                    //数量为零时删除这条数据
                    mGoodsDataBaseInterface.deleteSingle(getActivity(), numText, goodsid);
                }

                //设置总价和数量
                setAll();
            }

        });

    }

    public void getGoodsCarData() {

        setAll();
        Log.e("TAG", "获取购物车数据");
    }


    /**
     * 动画结束后，更新所有数量和所有价格
     */
    class OnEndAnim implements GoodsAnimUtil.OnEndAnimListener {
        int goodsid;


        @Override
        public void onEndAnim() {

            //计算总价和数量
            setAll();
        }
    }


    /**
     * 设置商品总数和总价格
     */
    private void setAll() {
        //设置所有购物数量

        if (mGoodsDataBaseInterface.getGoodsNumberAll(getActivity(), Integer.parseInt(shopId.trim())) == 0) {
            //购物车中没有商品

            mListAllPrice.setText("￥0");
            mListAllNum.setText("0");


            mListAllNum.setEnabled(false);//数量圆球变灰
            btnGouWuche.setEnabled(false);//当数量等于0时小人变灰
            mListAllNum.setVisibility(View.GONE);
            mListSubmit.setEnabled(false);//提交按钮

        } else {//购物车有商品时计算
            //获取总价格
            double priceAll = mGoodsDataBaseInterface.getGoodsPriceAll(getActivity(), Integer.parseInt(shopId.trim()));
            mListAllPrice.setText("￥" + priceAll);

            //总数量
            int numberAll = mGoodsDataBaseInterface.getGoodsNumberAll(getActivity(), Integer.parseInt(shopId.trim()));
            mListAllNum.setText(numberAll + "");


            mListAllNum.setEnabled(true);//数量圆球变亮
            btnGouWuche.setEnabled(true);//当数量大于0时小人变亮
            mListAllNum.setVisibility(View.VISIBLE);
            mListSubmit.setEnabled(true);//提交按钮
        }
    }




    /**
     *  获取数据
     */
    private void setData() {

        ShopActivity shop = (ShopActivity) getActivity();
        shopImage = shop.getShopImage();
        shopName = shop.getShopName();
        sendfree=shop.getsendfree();
        userId = MyApplication.app.getUserId();

        ShopActivity activity = (ShopActivity) getActivity();
        shopId = activity.getShopId();
        Log.e("Life", "商家shopID---------------" + shopId);

        //从服务器加载左侧分类页面数据
        getSortDataFromServer(shopId);

    }



    /**
     * 从服务器加载分类数据
     *
     * @param shopId
     */
    private void getSortDataFromServer(String shopId) {

        String url = Contents.SORT_URL + shopId;
        RequestParams params = new RequestParams(url);
        Log.i("params", params + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    JSONObject obj = new JSONObject(result);
                    JSONArray array = obj.getJSONArray("foodtypelist");

                    //解析并封装实体类
                    mSorts = JSON.parseArray(array.toString(), ShopSortData.ShopDatalistBean.class);

                    //适配器   解析完数据再调用setAdapter
                    setSortAdapter();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "该商家暂无商品~", Toast.LENGTH_SHORT).show();
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });

    }


    /**
     * 加载分类内容数据
     *
     * @param shopId 商家唯一标示符
     * @param sortId 每个分类的ID
     */
    private void getContentDataFromServer(String shopId, String sortId, final int page) {

        //1100&shopid=1159&pagesize=20&pageindex=1xuy需要传入sortId和shopId
        String sortContenturl = Contents.SORT_CONTENT_URL + sortId + "&shopid=" + shopId + "&pagesize=20&pageindex=" + page;
        //参数
        RequestParams params = new RequestParams(sortContenturl);
        //post请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    JSONObject obj = new JSONObject(result);
                    JSONArray array = obj.getJSONArray("foodlist");

                    if (page == 1) {
                        mContents = JSON.parseArray(array.toString(), SortContentData.FoodlistBean.class);
                        if (mContents.size() == 0) {
                            lvContent.setVisibility(View.GONE);
                            tvNotGoods.setVisibility(View.VISIBLE);
                            return;
                        } else {
                            lvContent.setVisibility(View.VISIBLE);
                            tvNotGoods.setVisibility(View.GONE);
                        }
                        setSortContentAdapter();
                    } else {

                        mMoreContents = JSON.parseArray(array.toString(), SortContentData.FoodlistBean.class);
                        if (mMoreContents.size() == 0) {
                            ToastUtils.showMessageShort(getActivity(), "没有更多了哦");
                            return;
                        }
                        mContents.addAll(mMoreContents);
                        mMoreContents.clear();//清空以便下一次再用
                        mShopContentAdapter.notifyDataSetChanged();


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "暂时没有数据", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }


    /**
     * 初始化
     *
     * @param view
     * @param contentItem
     */
    private void setViews(View view, View contentItem) {

        lvSort = (ListView) view.findViewById(R.id.lv_sort_dishes);
        lvContent = (XRecyclerView) view.findViewById(R.id.lv_content_dishes);
        mListAllPrice = (TextView) view.findViewById(R.id.m_list_all_price);
        mListSubmit = (Button) view.findViewById(R.id.m_list_submit);
        mListAllNum = (TextView) view.findViewById(R.id.m_list_num);
        tvNotGoods = (TextView) view.findViewById(R.id.tv_not_goods);


        //购物车布局
        btnGouWuche = (Button) view.findViewById(R.id.m_list_car);//购物车小人
        mCarLay = (RelativeLayout) view.findViewById(R.id.m_list_car_lay);//购物车小人父控件布局
        llGoodsCar = (LinearLayout) view.findViewById(R.id.ll_goods_car);
        llGoodsCarBack = (LinearLayout) view.findViewById(R.id.ll_Goods_car_back);
        tvClearGoodsCar = (TextView) view.findViewById(R.id.clear_cart);
        lvGoodsCar = (RecyclerView) view.findViewById(R.id.lv_goods_car);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        lvGoodsCar.setLayoutManager(manager);
        lvGoodsCar.setItemAnimator(new DefaultItemAnimator());

        //XRecyclerView相关设置
        LinearLayoutManager manager2 = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        lvContent.setLayoutManager(manager2);

        //设置可刷新
        lvContent.setRefreshing(true);
        lvContent.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);//刷新样式
        lvContent.setLoadingMoreProgressStyle(ProgressStyle.Pacman);//加载更多样式

        //设置刷新和加载更多
        setXrecyclerData();

    }

    /**
     * 设置刷新和加载更多
     */
    private void setXrecyclerData() {

        lvContent.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getContentDataFromServer(shopId, sortId, 1);
                        lvContent.refreshComplete();
                    }
                },500);

            }

            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        getContentDataFromServer(shopId, sortId, page);
                        lvContent.loadMoreComplete();
                    }
                },500);

            }
        });
    }


    /**
     * ListView点击事件
     *
     * @param parent   listView
     * @param view
     * @param position 当前的item
     * @param id
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (parent.getId()) {

            case R.id.lv_sort_dishes://左边分类Item

                mShopSortAdapter.changeSelected(position);//刷新改变Item背景颜色

                //点击Item时获取当前Item的分类数据
                sortData = mSorts.get(position);
                sortId = sortData.getSortID();
                Log.i("商家sortId---------------", "" + sortId);

                //获取分类内容数据
                getContentDataFromServer(shopId, sortId, 1);
                break;

        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.clear_cart://清空购物车

                //清空
                mGoodsDataBaseInterface.deleteAll(getActivity());

                mShopContentAdapter.notifyDataSetChanged();
                setAll();
                hideGoodsCar();
                ToastUtils.showMessageShort(getActivity(), "清空购物车");

                break;

            case R.id.m_list_car://点击小人显示购物车

                //设置购物车
                setGoodsCar();

                break;
            case R.id.ll_Goods_car_back://隐藏购物车

                //隐藏
                hideGoodsCar();

                break;

            case R.id.m_list_submit://下单按钮
                mpackageFree = mContents.get(0).getPackageFree();
                String userId = MyApplication.app.getUserId();
                if (userId != null) {//跳转到订单页面
                    Intent intent = new Intent(getActivity(), OrderActivity.class);
                    intent.putExtra("shopName", shopName);
                    intent.putExtra("shopId", shopId);
                    intent.putExtra("shopImage", shopImage);
                    intent.putExtra("PackageFree", mpackageFree);//打包费
                    intent.putExtra("sendfree",sendfree);
                    startActivity(intent);
                } else {
                    ToastUtils.showMessageShort(getActivity(), "您还没有登录(⊙o⊙)哦");
                    StartLogInUtils.startLogIn(getActivity());
                }
                break;
        }
    }

    private String mpackageFree;


    /**
     * 隐藏购物车视图
     */
    private void hideGoodsCar() {
        llGoodsCar.setVisibility(View.GONE);
        TranslateAnimation anim = new TranslateAnimation(0, 0, 0, -llGoodsCar.getHeight());
        anim.setDuration(600);
        llGoodsCar.setAnimation(anim);
    }




    /**
     * 购物车
     */
    private void setGoodsCar() {
        //根据商家Id获取当前商家在购物车中的商品数据
        goodsBeens = mGoodsDataBaseInterface.getGoodsCarData(getActivity(), Integer.parseInt(shopId));

        if (llGoodsCar.getVisibility() == View.GONE) {//显示购物车
            llGoodsCar.setVisibility(View.VISIBLE);
            TranslateAnimation anim = new TranslateAnimation(0, 0, -llGoodsCar.getHeight(), 0);
            anim.setDuration(600);
            llGoodsCar.setAnimation(anim);
        } else {
            //隐藏
            hideGoodsCar();
        }

        llGoodsCar.setOnTouchListener(new View.OnTouchListener() {//拦截外面一层布局的监听事件
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        carAdapter = new GoodsCarAdapter(getActivity(), goodsBeens);
        lvGoodsCar.setAdapter(carAdapter);
        //设置购物车加减按钮监听器
        setGoodsCarListeners();
    }

    /**
     * 设置购物车加减按钮监听器
     *
     * @param
     */
    private void setGoodsCarListeners() {

        carAdapter.setOnItemClickListener(new GoodsCarAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void OnjiaClick(GoodsCarAdapter.MyViewHolder holder, int goodsid, String goodsName, String price) {

                int numText = Integer.parseInt(holder.tvGoodsNum.getText().toString().trim());
                int numner = mGoodsDataBaseInterface.saveGoodsNumber(getActivity(), Integer.parseInt(shopId), goodsid, goodsName, numText + 1 + "", price, userId);
                holder.tvGoodsNum.setText(numner + "");

                /** 执行动画 */
                GoodsAnimUtil.setAnim(getActivity(), holder.ivjia, mCarLay);

                /** 结束动画后   并统计购物总数和购物总价 */
                GoodsAnimUtil.setOnEndAnimListener(new OnEndAnim());
                mShopContentAdapter.notifyDataSetChanged();

            }

            @Override
            public void OnJianClick(GoodsCarAdapter.MyViewHolder holder, int goodsid, String goodsName, String price) {

                int numText = Integer.parseInt(holder.tvGoodsNum.getText().toString().trim());

                int number = mGoodsDataBaseInterface.saveGoodsNumber(getActivity(), Integer.parseInt(shopId), goodsid, goodsName, String.valueOf(numText - 1), price, userId);
                holder.tvGoodsNum.setText(number + "");


                /** 减完之后  数据为0 */
                numText = Integer.parseInt(holder.tvGoodsNum.getText().toString().trim());
                if (numText == 0) {
                    holder.tvGoodsNum.setVisibility(View.GONE);
                    holder.ivJian.setVisibility(View.GONE);
                    //删除当前商品
                    mGoodsDataBaseInterface.deleteSingle(getActivity(), numText + "", goodsid);
                    ToastUtils.showMessageShort(getActivity(), "数量为零，删除");
                    carAdapter.removeData(holder.getAdapterPosition());
                }
                setAll();
                mShopContentAdapter.notifyDataSetChanged();
            }
        });

    }

}
